﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Utilities.Menu.UIElements
{
    public class TextEdit
    {
        string text;
        int spacing, cursor_speed = 7, max_lenght;
        Vector2 position;
        SpriteFont font;
        Texture2D bg;

        public TextEdit(SpriteFont font, Texture2D bg, Vector2 position, int max_lenght)
        {
            this.position = position;
            this.font = font;
            this.max_lenght = max_lenght;
            this.bg = bg;

            spacing = (int)font.MeasureString("A").X;
            text = "";
        }

        public void AddChar(string chr)
        {
            if (text.Length < max_lenght)
                text += chr;
        }

        public void RemoveChar()
        {
            if (text.Length > 0)
                text = text.Substring(0, text.Count() - 1);
        }

        public void DrawTextEdit(GameTime gt, SpriteBatch sprite_batch)
        {
            int w = sprite_batch.GraphicsDevice.Viewport.Width;
            position.X = w / 2 - font.MeasureString(text+"_").X / 2;
            float alpha = (float)Math.Sin(gt.TotalGameTime.TotalSeconds * cursor_speed);
            sprite_batch.Draw(bg, new Vector2(w / 2 - bg.Width / 2, position.Y - (bg.Height - font.MeasureString("A").Y) / 2.0f), 
                Color.White);
            sprite_batch.DrawString(font, text, position, Color.White);
            sprite_batch.DrawString(font, "_", position + Vector2.UnitX * spacing * (text.Length), Color.White * alpha);
        }

        public void DrawTextEdit(GameTime gt, SpriteBatch sprite_batch, float alpha)
        {
            int w = sprite_batch.GraphicsDevice.Viewport.Width;
            position.X = w / 2 - font.MeasureString(text + "_").X / 2;
            float a = (float)Math.Sin(gt.TotalGameTime.TotalSeconds * cursor_speed);
            sprite_batch.Draw(bg, new Vector2(w / 2 - bg.Width / 2, position.Y - (bg.Height - font.MeasureString("A").Y) / 2.0f), Color.White * alpha);
            sprite_batch.DrawString(font, text, position, Color.White * alpha);
            sprite_batch.DrawString(font, "_", position + Vector2.UnitX * spacing * (text.Length), Color.White * a);
        }

        public string Text
        {
            get { return text; }
        }
    }
}
